package ru.dc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by IntelliJ IDEA.
 * User: deady
 * Date: 03.11.2010
 * Time: 23:34:07
 * To change this template use File | Settings | File Templates.
 */
public class ExternalConnectionsListener extends Thread {

    private boolean stopRequested = false;
    private Log logger = LogFactory.getLog(getClass());

    @Override
    public void run() {
        int port = Application.getApplication().getSettings().getTcpPort();
        ServerSocket s = null;
        try {
            s = new ServerSocket(port);
            logger.info("Started listening tcp connections on port "+port);
        } catch (IOException e) {
            logger.error("Can't start listening tcp connections on port "+port, e);
            return;
        }

        while (!stopRequested) {
            try {
                Socket incoming = s.accept();
                logger.info("Accepted connection from "+incoming.getInetAddress());
                IncomingClientConnection conn = new IncomingClientConnection(incoming);
                conn.setNick(Application.getApplication().getSettings().getNick());
                conn.connect();
            } catch (IOException e) {
                logger.error("Can't answer on connection", e);
            }

        }

    }


    public void requestStop() {
        stopRequested = true;
    }
}
